<?php
/***/
namespace app\admin\controller;

use app\admin\model\Channel;
use think\Db;
use think\facade\Config;

/**
 * 关键字配置
 */
class BalanceShift extends Father {
	/**
	 * 首页
	 * @Author   lf
	 * @DateTime 2019-05-30T14:29:31+0800
	 * @param    [type]                   $notfield [description]
	 * @return   [type]                             [description]
	 */
	public function index() {
		if (request()->isPost()) {
			$request = request()->only(['limit', 'cha' => '']);

			$bus = new Channel;

			$getData = $bus->withSearch(['off_redis'])
				->field('channel_id,company_name,sms_balance')
				->where('p_id', session('relate_id'))
				->where('p_id', '<>', 0);
			if ($request['cha']) {
				$getData = $getData->where('channel_id', $request['cha']);
			}
			$getData = $getData->paginate($request['limit'], false, ['query' => $request])
				->each(function ($item, $key) {
					$item->company_name = $item->channel_id . '/' . $item->company_name;
				})->toarray();

			return json([
				"code"  => 0,
				"msg"   => "",
				"count" => $getData['total'],
				"data"  => $getData['data'],
			]);

		} else {
			$bus = new Channel;

			//选择的账号
			$channelData = $bus->withSearch(['off_redis'])->field('channel_id,company_name')->where('p_id', session('relate_id'))->where('p_id', '<>', 0)->select();
			$this->assign('channels', $channelData);
			//“我的”余额
			$infoData = $bus->withSearch(['off_redis'])->field('oevrplus,sms_balance')->where('channel_id', session('relate_id'))->find();

			if (in_array(session('channel_level'), [1, 4])) {

				$this->assign('infoData', ['oevrplus' => $infoData['oevrplus'] . '元', 'sms_balance' => 0 . '条']);
			} else {
				$this->assign('infoData', ['oevrplus' => $infoData['sms_balance'] . '条', 'sms_balance' => $infoData['sms_balance'] . '条']);
			}

			//初始表格
			$config = [
				['field' => 'company_name', 'title' => '子账户']
				, ['field' => 'sms_balance', 'title' => '短信余额（条）']
				, ['fixed' => 'right', 'title' => '操作', 'toolbar' => '#barDemo', 'unresize' => 'true'],
			];

			$this->assign('configTable', json_encode($config, JSON_UNESCAPED_UNICODE));

			//可用条数
			$channelCk = $bus->withSearch(['off_redis'])->field('sum(sms_balance) sum_balance')->where('p_id', session('relate_id'))->find();
			//计算总条数
			$channelOneSumBalance = 0;
			$this->assign('smsBalance', bcsub($channelOneSumBalance, $channelCk['sum_balance']) . '条');

			return $this->fetch();
		}
	}
	/**
	 * 充值
	 * @Author   lf
	 * @DateTime 2018-06-28T16:03:00+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_add() {

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			//接参
			$channel_id  = trim(input('post.channel_id'));
			$rechargenum = intval(input('post.rechargenum'));
			$remarks     = trim(input('post.remarks'));

			//检查字段
			if (!is_numeric($rechargenum) || $rechargenum <= 0) {
				return '请输入正确的充值条数';
			}

			//父
			$relate_id = session('relate_id');

			$channelm = new Channel;
			//查询父情况
			$channelOne = $channelm->where('channel_id', $relate_id)->find();

			//1,4类账号使用余额
			// if (in_array($channelOne['level'], [1, 4])) {
			// } elseif ($channelOne['level'] == 2) {
			// 	if ($channelOne['sms_balance'] < $rechargenum) {
			// 		return '可用余额不足';
			// 	}
			// } else {
			// 	return 'error';
			// }

			trace(session('username') . '充值条数，目标：' . $channel_id . '；数目：' . $rechargenum);
			// 启动事务
			Channel::startTrans();
			try {
				//子账户加款
				$user = Channel::get(['channel_id' => $channel_id]);

				$data1['channel_id']     = $channel_id;
				$data1['note_num_ago']   = $user->sms_balance; //调整前数目
				$data1['note_num_now']   = bcadd($user->sms_balance, $rechargenum); //调整后数目
				$data1['operation_type'] = '1'; //3转移余额
				$data1['operation_num']  = $rechargenum;
				$data1['remarks']        = $remarks;
				$data1['operation_user'] = session('user_id');
				$data1['operation_time'] = date('Y-m-d H:i:s');
				//添加记录
				Db::table('bus_record')->insert($data1);

				$user->sms_balance = ['inc', $rechargenum];
				$res1              = $user->save();

				if (!in_array(session('channel_level'), [1, 4])) {
					//我的账号减款
					$user                    = Channel::get(['channel_id' => $relate_id]);
					$data1['channel_id']     = $relate_id;
					$data1['note_num_ago']   = $user->sms_balance; //调整前数目
					$data1['note_num_now']   = bcsub($user->sms_balance, $rechargenum); //调整后数目
					$data1['operation_type'] = '3'; //3转移余额
					$data1['operation_num']  = $rechargenum;
					$data1['remarks']        = '转给' . $channel_id;
					$data1['operation_user'] = session('user_id');
					$data1['operation_time'] = date('Y-m-d H:i:s');
					//添加记录
					Db::table('bus_record')->insert($data1);

					$user->sms_balance = ['dec', $rechargenum];
					$res2              = $user->save();
					//先减去REDIS
					// $this->redisCrlT('del', $relate_id, $rechargenum);
				} else {
					$res2 = 1;
				}

				if ($res1 && $res2) {
					// 提交事务
					Db::commit();
					//添加REDIS
					// $this->redisCrlT('add', $channel_id, $rechargenum);
					return 'success';
				} else {
					// 回滚事务
					Db::rollback();
					if (!in_array(session('channel_level'), [1, 4])) {
						//不成事就加回REDIS
						// $this->redisCrlT('add', $relate_id, $rechargenum);
					}
					return '充值失败';
				}

			} catch (Exception $e) {
				// 回滚事务
				Db::rollback();
				trace(session('username') . '充值失败：' . $e->getMessage(), 'error');
			}

			return '充值失败';
		}

		$channel_id = trim(input('get.channel_id'));

		$this->assign('channel_id', $channel_id);

		//可用
		//“我的”余额
		$infoData = Channel::field('oevrplus,sms_balance')->where('channel_id', session('relate_id'))->find();

		$this->assign('oevrplus', $infoData['oevrplus']);

		return $this->fetch('add');
	}

	/**
	 * 调价
	 * @Author   lf
	 * @DateTime 2018-06-29T15:55:14+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_adjust() {
	}

	/**
	 * 退款
	 * @Author   lf
	 * @DateTime 2018-07-03T14:39:57+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_refund() {
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$channel_id = trim(input('post.channel_id'));
			$refundnum  = intval(input('post.refundnum'));
			$remarks    = trim(input('post.remarks'));
			$relate_id  = session('relate_id');

			if (!is_numeric($refundnum) || $refundnum <= 0) {
				return '请输入正确的充值条数';
			}

			trace(session('username') . '退回充值条数，目标：' . $channel_id . '；数目：' . $refundnum);
			// 启动事务
			Channel::startTrans();
			try {
				//子账户加款
				$user = Channel::get(['channel_id' => $channel_id]);

				$data1['channel_id']     = $channel_id;
				$data1['note_num_ago']   = $user->sms_balance; //调整前数目
				$data1['note_num_now']   = bcsub($user->sms_balance, $refundnum); //调整后数目
				$data1['operation_type'] = '4'; //3转移余额
				$data1['operation_num']  = $refundnum;
				$data1['remarks']        = $remarks;
				$data1['operation_user'] = session('user_id');
				$data1['operation_time'] = date('Y-m-d H:i:s');
				//添加记录
				Db::table('bus_record')->insert($data1);

				$user->sms_balance = ['dec', $refundnum];
				$res1              = $user->save();
				//先减去
				// $this->redisCrlT('del', $channel_id, $refundnum);

				//不是1,4级不需要加回款
				if (!in_array(session('channel_level'), [1, 4])) {
					//我的账号减款
					$user                    = Channel::get(['channel_id' => $relate_id]);
					$data1['channel_id']     = $relate_id;
					$data1['note_num_ago']   = $user->sms_balance; //调整前数目
					$data1['note_num_now']   = bcadd($user->sms_balance, $refundnum); //调整后数目
					$data1['operation_type'] = '1'; //3转移余额
					$data1['operation_num']  = $refundnum;
					$data1['remarks']        = $channel_id . '退回';
					$data1['operation_user'] = session('user_id');
					$data1['operation_time'] = date('Y-m-d H:i:s');
					//添加记录
					Db::table('bus_record')->insert($data1);

					$user->sms_balance = ['inc', $refundnum];
					$res2              = $user->save();
				} else {
					$res2 = 1;
				}

				if ($res1 && $res2) {
					// 提交事务
					Db::commit();
					if (!in_array(session('channel_level'), [1, 4])) {
						//添加REDIS
						// $this->redisCrlT('add', $relate_id, $refundnum);
					}
					return 'success';
				} else {
					// 回滚事务
					Db::rollback();
					//先减去
					// $this->redisCrlT('add', $channel_id, $refundnum);
					return '充值失败';
				}

			} catch (Exception $e) {
				// 回滚事务
				Db::rollback();
				trace(session('username') . '退回失败：' . $e->getMessage(), 'error');
			}
			return '充值失败';
		}

		$channel_id = trim(input('get.channel_id'));

		$this->assign('channel_id', $channel_id);
		return $this->fetch('refund');
	}
	/**
	 * redis原子操作增删(条数)
	 * @Author   lf
	 * @DateTime 2019-07-12T10:02:16+0800
	 * @param    [type]                   $sem [description]
	 * @param    [type]                   $num [description]
	 * @return   [type]                        [description]
	 */
	public function redisCrlT($sem, $cid, $num) {
		// $ZD_REDIS_CONFIG = Config::get('ZD_REDIS_CONFIG');
		// //连接本地的 Redis 服务
		// $redis = new \Redis();
		// $redis->connect($ZD_REDIS_CONFIG['IP'], $ZD_REDIS_CONFIG['PORT']);
		// $redis->auth($ZD_REDIS_CONFIG['PASSWORD']); //密码
		// $redis->select(4);

		// $renum = $redis->get('T_' . $cid);

		// if ($renum == '' || $renum == null) {
		// 	trace('渠道' . $cid . '的之前的条数是：' . $renum . '，终止添加redis');
		// 	return;
		// }
		// switch ($sem) {
		// case 'add':

		// 	trace('渠道' . $cid . '的Redis增加条数（单位 条）：' . $num);

		// 	$redisnum = $redis->Incr('T_' . $cid, $num);

		// 	trace('渠道' . $cid . '的Redis增加条数后的数字：' . $redisnum);
		// 	//
		// 	return $redisnum;
		// 	break;
		// case 'del':

		// 	trace('渠道' . $cid . '的Redis减去条数（单位 条）：' . $num);

		// 	$redisnum = $redis->Decr('T_' . $cid, $num);

		// 	trace('渠道' . $cid . '的Redis减去条数后的数字：' . $redisnum);

		// 	return $redisnum;
		// 	break;

		// default:
		// 	exit('无法识别操作');
		// 	break;
		// }

	}
}